package org.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.wxpay.sdk.WXPay;
import org.example.config.MyWXPayConfig;
import org.example.domain.dto.GoodsMessage;
import org.example.domain.dto.Pays;
import org.example.domain.entity.Order;
import org.example.domain.model.Result;
import org.example.service.IOrderService;
import org.example.util.AliPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/*
szy

*/
@Controller
@CrossOrigin("*")

public class TestPayController {


    @Resource
    private AliPayUtil aliPayUtil;

    @Resource
    private IOrderService iOrderService;

    @ResponseBody
    @RequestMapping(value = "/pay", method = RequestMethod.POST, consumes = "application/json")
    public String pay (@RequestBody String pays) throws IOException {
        System.out.println(pays);
        JSONObject jsonObject = JSONObject.parseObject(pays);
        JSONObject json = jsonObject.getJSONObject("pays");


        Pays pay = json.toJavaObject(Pays.class);
        System.out.println(pay);
        Map map = new HashMap();
        map.put("orderId",pay.getOrderId());
        map.put("totalPrice",pay.getTotalPrice());
        String alipay = aliPayUtil.alipay(map);
//        return Result.buildSuccess(alipay);
        iOrderService.updateStatus(pay.getOrderId());
        return alipay;
    }

    @ResponseBody
    @PostMapping("/wxPay")
    public Result wxPay (@RequestBody String pays) throws IOException {
        //获取前端返回的订单编号和价格
        JSONObject jsonObject = JSONObject.parseObject(pays);
        JSONObject json = jsonObject.getJSONObject("pays");
        Pays pay = json.toJavaObject(Pays.class);


        //微信支付：申请支付连接
        WXPay wxPay = new WXPay(new MyWXPayConfig());

        //在data集合中存储生成微信二维码的重要参数
        HashMap<String, String> data = new HashMap<>();

        //查支付所需要的必要参数
        Order order = iOrderService.queryByOne(pay.getOrderId());

        //订单号加流水号（让订单可重复支付）
        String temStr = order.getOrderId() + (System.currentTimeMillis() + "").substring(10);

        data.put("body", order.getUntitled()); //支付说明
        data.put("out_trade_no", temStr); //使用当前用户订单的编号作为当前支付交易的交易号
        data.put("fee_type", "CNY"); //支付模式为人民币
        data.put("total_fee", "1"); //设置支付金额为1分
        data.put("trade_type", "NATIVE"); //交易的类型
        //内网穿透id: 844568725e0a1f62
        data.put("notify_url", "http://7v6hyh.natappfree.cc/wxPay/success"); //设置支付完成时回调方法的接口

        //用于储存返回给前端必要数据的map集合（按需添加但是一般订单价格，订单编号，支付二维码编号都是必须的）

        HashMap<String, String> map = new HashMap<>();
        //储存订单编号
        map.put("number", temStr);
        //储存订单价格
        map.put("price", order.getActualAmount().toString());

        try {
            //通过data集合中的重要参数请求微信服务器，然后微信服务器将参数封装到resp中
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //通过微信服务器返回的数据得到微信支付二维码，然后通过map集合返回给前端
            map.put("resp", resp.get("code_url"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.buildSuccess(map, "success");
    }
}
